<template>


  <div>
    <button @click="add">新增</button>
    <div v-for="(item, index) in data" :key="index">
      商品名：{{ item.name }} --- 价格：{{ item.price }} --- 库存：{{ item.inventory }}
      <button @click="update(item)">修改</button>
      <button @click="del(item)">删除</button>
    </div>
  </div>

  <div class="form" v-if="open">
    新增
    商品名 <input type="text" v-model="createParams.name">
    价格 <input type="number" v-model="createParams.price">
    库存 <input type="number" v-model="createParams.inventory">
    <br>
    <button @click="submit">提交</button>
  </div>

  <div class="form" v-if="updateOpen">
    更新
    商品名 <input type="text" v-model="createParams.name">
    价格 <input type="number" v-model="createParams.price">
    库存 <input type="number" v-model="createParams.inventory">
    <br>
    <button @click="updateSubmit">更新</button>
  </div>

</template>

<script>
import {goods} from "./api/goods";

export default {

  methods: {
    async updateSubmit() {
      this.updateOpen = false
      await goods.updateGoods(this.createParams.id, this.createParams)
      this.$forceUpdate();
      this.createParams = {}
    },
    async submit() {
      this.open = false
      await goods.createGoods(this.createParams)
      this.$forceUpdate();
      this.createParams = {}
    },
    add() {
      this.open = true
    },
    update(item) {
      this.updateOpen = true
      this.createParams.name = item.name
      this.createParams.price = item.price
      this.createParams.inventory = item.inventory
      this.createParams.id = this.data.indexOf(item)
    },
    async del(item) {
      console.log(item)
      goods.delGoods(this.data.indexOf(item))
      this.$forceUpdate();
    }
  },
  data() {
    return {
      createParams: {
        id: 0,
        name: '',
        price: 0,
        inventory: 0
      },
      open: false,
      updateOpen: false,
      data: []
    }
  },

  async created() {
    this.data = await goods.getGoods()
    this.$forceUpdate();
  },
  async updated() {
    this.data = await goods.getGoods()
  }

}

</script>


<style scoped>
.form {
  display: flex;
  flex-direction: column;

  box-shadow: 5px 5px black;
  border-radius: 20px;
  position: fixed;
  top: 40%;
  left: 60%;
  width: 400px;
  height: 220px;
  transition: width 10s linear 2s;
  background: rgba(89, 87, 87, 0.9);
  color: white;
  padding: 20px;
}
</style>
